package com.tlm.consumer;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

public class myFuzai extends AbstractLoadBalancerRule {
    int cishu = 0;
    int jiqi = 0;
    //改造随机算法为轮询算法，并且每台机器轮询5次在切换机器。
public Server choose(ILoadBalancer lb, Object key) {
 if (lb == null) {
        return null;
    }
    Server server = null;

        while (server == null) {
        if (Thread.interrupted()) {
            return null;
        }
        List<Server> upList = lb.getReachableServers();
        List<Server> allList = lb.getAllServers();

        int serverCount = allList.size();
        if (serverCount == 0) {


            return null;
        }

//        int index = chooseRandomInt(serverCount);
            if(cishu<5){
                server = upList.get(jiqi);
                cishu++;
            }else{
                jiqi++;
                cishu=0;
                if(jiqi>=serverCount){
                    jiqi=0;
                }
            }

        if (server == null) {

            Thread.yield();
            continue;
        }

        if (server.isAlive()) {
            return (server);
        }

        // Shouldn't actually happen.. but must be transient or a bug.
        server = null;
        Thread.yield();
    }

        return server;

}

    protected int chooseRandomInt(int serverCount) {
        return ThreadLocalRandom.current().nextInt(serverCount);
    }


    @Override
    public Server choose(Object key) {
        return choose(getLoadBalancer(), key);
    }

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }
}
